#include <iostream>
#include <string>
#include <uv.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>

#include "spider.h"
#include "log.h"
#include "src/define.h"

const std::string SERVICE_NAME = "spider";
bool g_isRunning;

void PrintVersionInfo()
{
    std::cout << SERVICE_NAME << " v" << SPIDER_VERSION << " Build in " << __DATE__ << " " << __TIME__ << std::endl;
}

bool ParseProgmaOptions(int nArgc, char **szArgs)
{
    for (int i = 1; i < nArgc; ++i)
    {
        if (szArgs[i] == std::string("-h") || szArgs[i] == std::string("--help"))
        {
            std::cout << "Usage:\n"
                         "    --help,-h                 Print help message\n"
                         "    --version,-v              Print version info\n"
                         "    --uuid,-u [string]        Uuid\n"
                         "    --addr,-a [string]        Server addr\n"
                         "    --port,-p [string]        Server port\n"
                         "    --bind,-b [string]        Bind Addr\n"
                      << std::endl;
            exit(0);
        }
    }
    for (int i = 1; i < nArgc; ++i)
    {
        if (szArgs[i] == std::string("-v") || szArgs[i] == std::string("--version"))
        {
            PrintVersionInfo();
            exit(0);
        }
    }
    for (int i = 1; i < nArgc - 1; ++i)
    {
        if (szArgs[i] == std::string("-u") || szArgs[i] == std::string("--uuid"))
        {
            g_Uuid = szArgs[i + 1];
        }
        if (szArgs[i] == std::string("-a") || szArgs[i] == std::string("--addr"))
        {
            g_Addr = szArgs[i + 1];
        }
        if (szArgs[i] == std::string("-p") || szArgs[i] == std::string("--port"))
        {
            g_Port = szArgs[i + 1];
        }
        if (szArgs[i] == std::string("-b") || szArgs[i] == std::string("--bind"))
        {
            g_BindAddr = szArgs[i + 1];
        }
    }
    return true;
}

void application_signal_stop(int nSignal)
{
    (void)nSignal;
    Spider::GetInstance().Stop();
    g_isRunning = false;
}

int main(int nArgc, char **szArgs)
{
    signal(SIGQUIT, application_signal_stop);
    signal(SIGTERM, application_signal_stop);

    ParseProgmaOptions(nArgc, szArgs);

    if (!Spider::GetInstance().Start())
    {
        LOG_ERROR("Spider Start failed");
        return -1;
    }
    g_isRunning = true;
    while(g_isRunning) {
        sleep(1);
    }
    return 0;
}